package com.xpec.cipher.h5handler;

import java.util.Random;

import com.xpec.cipher.CipherConnectionConstant;
import com.xpec.cipher.CipherHandler;
import com.xpec.cipher.handler.CipherConnectionPacketHandler;
import com.xpec.cipher.tals.TalsConstance;
import com.xpec.cipher.tals.record.ServerHelloRecord;

public class H5ServerChangeCipherHandler implements CipherConnectionPacketHandler
{
	private Random random = new Random(System.currentTimeMillis());

	@Override
	public void receiveHandle(CipherHandler cipherHandler)
	{
		// 接收到的是Client发过来的非HandShake包
		int contentType = cipherHandler.readUnsignedByteFromRealContent();
		if (contentType == TalsConstance.CONTENT_TYPE_NO_HAND_SHAKE)
		{
			int handShakeType = cipherHandler.readUnsignedByteFromRealContent();
			if (handShakeType == TalsConstance.HAND_SHAKE_TYPE_CLIENT_HELLO)
			{
				// 读取client hello
				byte[] clientRandom = new byte[TalsConstance.CLIENT_HELLO_SIZE];
				cipherHandler.readByteFromRealContent(clientRandom);

				// 记录一下client的随机数
				cipherHandler.setParameter(CipherConnectionConstant.PARA_KEY_CLIENT_RANDOM,
					clientRandom);

				// 随机生成并发送server hello
				byte[] serverRandom = new byte[TalsConstance.SERVER_HELLO_SIZE];
				random.nextBytes(serverRandom);

				// 记录一下server的随机数
				cipherHandler.setParameter(CipherConnectionConstant.PARA_KEY_SERVER_RANDOM, serverRandom);

				// 发送Server的HandShakeRecord
				ServerHelloRecord helloRecord = new ServerHelloRecord(serverRandom);
				// 直接发送给外层的链条了
				cipherHandler.sendData(helloRecord.resolve(), false);
				
				// filterChain.packetSend(helloPacket);

//				cipherHandler.sendData(rsaKeyRecord.resolve(), true);

				System.out.println("handShake finish!");
			}
		}
	}

	@Override
	public void sendHandle(CipherHandler cipherHandler)
	{
		cipherHandler.passMessage(CipherHandler.PASS_MESSAGE_SEND);
	}

}
